//
//  HLOAuthController.swift
//  weibo-snh
//
//  Created by 黄力 on 15/12/14.
//  Copyright © 2015年 HLTest. All rights reserved.
//

import UIKit
import AFNetworking
import SVProgressHUD

class HLOAuthController: UIViewController,UIWebViewDelegate {
    
    var webView: UIWebView?
    
    //将加载view设置为webView
    override func loadView() {
        webView = UIWebView()
        //设置代理
        webView?.delegate = self
        view = webView
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        //添加左上角关闭按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "clickCloseBtn")
        //添加自动填充按钮
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "clickAutoBtn")
        //webView请求网络数据
        loadURLRequest()
    }
    
    //webView请求网络数据
    private func loadURLRequest () {
        //拼接请求的字符串
        let urlStr = "https://api.weibo.com/oauth2/authorize?client_id=" + OAuthAppKey + "&redirect_uri=" + OAuthAppRedirect
        //获取URL
        let url = NSURL(string: urlStr)
        //请求界面
        if let u = url {
            webView?.loadRequest(NSURLRequest(URL: u))
        }
    }

    //点击关闭按钮调用
    @objc func clickCloseBtn () {
        dismissViewControllerAnimated(true, completion: nil)
    }
    //点击自动填充按钮
    @objc func clickAutoBtn () {
        //执行javascript代码,自动填充账号密码
        webView?.stringByEvaluatingJavaScriptFromString("document.getElementById('userId').value = '15572595921',document.getElementById('passwd').value = 'qwe5237972'")
    }
}

//实现webView的代理方法
extension HLOAuthController {
    //当将要加载请求时调用
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //判断是否有请求的网址,如果没有就不去请求
        guard let _ = request.URL?.absoluteString else{
            return false
        }
        //获取网址字符串
        let urlStr = (request.URL?.absoluteString)!
        //判断如果是授权界面就直接执行
        if urlStr.hasPrefix("https://api.weibo.com/oauth2/authorize") {
            return true
        }
        //判断如果是回调网址界面就拦截
        if urlStr.hasPrefix("https://www.baidu.com") {
            print("拦截")
            //获取用户的code
            let codeStr = (request.URL?.query)!
            //截取字符串,abcde相当于站位符
            let code = codeStr.substringFromIndex("abcde".endIndex)
            //请求token
            HLUserAccountViewModel().loadUserToken(code,finshed: {(success: Bool) -> () in
                //移除加载视图
                SVProgressHUD.dismiss()
                //如果加载成功
                if success {
                    //完成后发送通知更改根控制器,因为通知是同步进行,实际上是让上一个控制器执行dismiss操作,
                    //所以会导致dismiss并没有执行完成就修改了根控制器,导致覆盖多层控制器在页面上
                    //所以将发送通知放在dismiss的回调上
                    self.dismissViewControllerAnimated(false, completion: { () -> Void in
                        //发送通知
                        NSNotificationCenter.defaultCenter().postNotificationName(MainWindowRootControllerChangeNotification, object: nil)
                    })
                    
                    //关闭控制器
//                    self.clickCloseBtn()
                }
                
            })
            
        }
        return false
    }
    
    //当开始加载时调用
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    //加载结束调用
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
}
